from datetime import timedelta
from openpyxl import load_workbook

from cfg import num_chars


def save_excel(df, out_filename):
    # 加载模板
    wb = load_workbook('input/meter_header.xlsx')
    sheet = wb.active
    df['姓名'] = df['姓名'].astype(str)
    df['身份证'] = df['身份证'].astype(str)
    for i, r in df.iterrows():
        row = list(df.loc[i])
        sheet.append(row)
    wb.save(out_filename)


def cala_workday(time_day):
    """
    # 获取上一个工作日
    """
    next_worker_day = ""

    # 最多查询20次
    query_time = 0

    while True:
        time_day = time_day + timedelta(days=1)

        if is_workday(time_day):
            next_worker_day = time_day.strftime("%Y-%m-%d")
            break
        elif query_time > 31:
            break

        query_time += 1

    return next_worker_day


def findText(msg):
    index = msg.index('扣')
    msg = msg[index + 1:].strip()
    if msg.__contains__('加'):
        char = msg.split('加')
        num = int(num_chars.get(char[0]))
        num2 = int(num_chars.get(char[1]))
        return num + num2
    elif msg.__contains__('减'):
        char = msg.split('减')
        num = int(num_chars.get(char[0]))
        num2 = int(num_chars.get(char[1]))
        return num - num2
    else:
        return num_chars.get(msg)
